package org.bluesky.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.bluesky.framework.ResponseResult;
import org.bluesky.framework.constants.SystemConstants;
import org.bluesky.framework.entity.Menu;
import org.bluesky.framework.entity.RoleMenu;
import org.bluesky.framework.mapper.MenuMapper;
import org.bluesky.framework.service.MenuService;
import org.bluesky.framework.service.RoleMenuService;
import org.bluesky.framework.service.RoleService;
import org.bluesky.framework.utils.BeanCopyUtils;
import org.bluesky.framework.utils.SecurityUtils;
import org.bluesky.framework.vo.MenuListVo;
import org.bluesky.framework.vo.MenuRoleVo;
import org.bluesky.framework.vo.MenuVo;
import org.bluesky.framework.vo.CheckMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单权限表(Menu)表服务实现类
 *
 * @author makejava
 * @since 2023-02-20 20:32:52
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private RoleService roleService;
    @Override
    public List<String> selectPermsByUserId(Long id) {
        //如果是管理返回所有权限
        if(SecurityUtils.isAdmin()){
            LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Menu::getMenuType,SystemConstants.MENU,SystemConstants.BUTTON);
            queryWrapper.eq(Menu::getStatus, SystemConstants.STATUS_NORMAL);
            List<Menu> menus = list(queryWrapper);
            List<String> perms = menus.stream()
                    .map(Menu::getPerms)
                    .collect(Collectors.toList());
            return perms;
        }
        List<String> permissions = getBaseMapper().selectPermissionByUserId(id);
        //否则返回所具有的权限
        return permissions;
    }

    @Override
    public List<MenuVo> selectRouterMenuTreeByUserId(Long userId) {
        MenuMapper menuMapper = getBaseMapper();
        List<MenuVo> menuList = null;
        //判断是否是管理员
        //如果是 返回符合要求的所有menus
        //如果不是 当前用户所具有的menu
        if(SecurityUtils.isAdmin()){
            menuList = menuMapper.selectAllRouterMenu();
        }else{
            menuList = menuMapper.selectRouterMenuTreeByUserId(userId);
        }
        //构建tree
        //先找出第一层的菜单，然后在去找他们的子菜单设置到children属性中
        List<MenuVo> menuTree = buildMenuTree(menuList,0L);
        return menuTree;
    }

    private List<MenuVo> buildMenuTree(List<MenuVo> menus,Long parentId){
        List<MenuVo> menuTree = menus.stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                .peek(menu -> menu.setChildren(getChildren(menu, menus)))
                .collect(Collectors.toList());
        return menuTree;
    }

    /**
     * 获取当前menu的子menu
     * @param menu
     * @return
     */
    private List<MenuVo> getChildren(MenuVo menu,List<MenuVo> menus){
        List<MenuVo> menuList = menus.stream()
                .filter(mv -> mv.getParentId().equals(menu.getId()))
                .peek(mv->mv.setChildren(getChildren(mv,menus)))
                .collect(Collectors.toList());
        return menuList;
    }

    @Override
    public ResponseResult getMenuList(String name,String status) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(name),Menu::getMenuName,name);
        if(StringUtils.hasText(status)){
            queryWrapper.eq(Menu::getStatus,status);
        }
        queryWrapper.orderByAsc(Menu::getParentId,Menu::getOrderNum);
        List<Menu> list = list(queryWrapper);
        List<MenuListVo> menuListVos = BeanCopyUtils.copyBeanList(list, MenuListVo.class);
        return ResponseResult.okResult(menuListVos);
    }

    @Override
    public ResponseResult deleteMenu(Long menuId) {
        Menu menu = getById(menuId);
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getParentId,menuId);
        List<Menu> list = list(queryWrapper);
        if(list.isEmpty()){
            removeById(menu.getId());
            return ResponseResult.okResult();
        }
        return ResponseResult.errorResult(500,"存在子菜单不允许删除");
    }

    @Override
    public ResponseResult treeMenuById(Long id) {
        List<MenuRoleVo> menuTree = roleService.treeMenuSelect();
        //被选中的权限
        LambdaQueryWrapper<RoleMenu> roleMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleMenuLambdaQueryWrapper.eq(RoleMenu::getRoleId,id);
        List<RoleMenu> roleMenus = roleMenuService.list(roleMenuLambdaQueryWrapper);
        List<Long> menuIds = roleMenus.stream()
                .map(RoleMenu::getMenuId)
                .collect(Collectors.toList());
        CheckMenuVo roleMenuVo = new CheckMenuVo(menuTree,menuIds);
        return ResponseResult.okResult(roleMenuVo);
    }
}

